package com.xuecheng.basic.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.basic.domain.Category;
import com.xuecheng.basic.mappers.CategoryMapper;
import com.xuecheng.basic.service.CategoryService;
import com.xuecheng.commons.model.vo.CategoryVo;
import com.xuecheng.commons.model.vo.ResponseResult;
import com.xuecheng.commons.utils.BeanHelper;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 课程分类 服务实现类
 * </p>
 *
 * @author itheima
 * @since 2022-07-17
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {
    /**
     * @description: 获取分类信息
     * @param: []
     * @return: com.xuecheng.commons.model.vo.ResponseResult<CategoryVo>
     * @author Keson
     * @date: 2022/7/17 15:59
     */
    @Override
    public ResponseResult findTreeNodes() {
        //根节点
        LambdaQueryWrapper<Category> qw = new LambdaQueryWrapper<>();
        qw.eq(Category::getParentid, 0);
        Category rootNode = this.getOne(qw);
        //转化为vo对象
        CategoryVo rootNodeVo = BeanHelper.copyProperties(rootNode, CategoryVo.class);

        //二级节点
        List<CategoryVo> twoNodeVo = this.findByParentId(rootNodeVo.getId());
        rootNodeVo.setCategoryTreeNodes(twoNodeVo);

        //三级节点
        twoNodeVo.forEach(data -> {
            List<CategoryVo> threeNodeVo = findByParentId(data.getId());
            data.setCategoryTreeNodes(threeNodeVo);
        });

        return ResponseResult.okResult(rootNodeVo);
    }

    //根据ParentId查询分类信息
    private List<CategoryVo> findByParentId(String id) {
        LambdaQueryWrapper<Category> qw = new LambdaQueryWrapper<>();
        qw.eq(Category::getParentid, id);
        List<Category> list = this.list(qw);
        List<CategoryVo> categoryVos = BeanHelper.copyWithCollection(list, CategoryVo.class);
        return categoryVos;
    }
}
